<template>
	<view class="publish-page">
		<!-- 授权类型选择 -->
		<view class="auth-types">
			<view class="auth-card" :class="{ 'active': selectedType === 'token' }" @click="selectType('token')">
				<view class="auth-title">个人访问令牌</view>
				<view class="auth-desc" :class="{ 'green-text': selectedType === 'token' }">配置简单</view>
				<view class="auth-limit" :class="{ 'green-text': selectedType === 'token' }">有效期最多30天</view>
			</view>

			<view class="auth-card" :class="{ 'active': selectedType === 'oauth' }" @click="selectType('oauth')">
				<view class="auth-title">OAuth 应用</view>
				<view class="auth-desc" :class="{ 'green-text': selectedType === 'oauth' }">配置灵活</view>
				<view class="auth-limit" :class="{ 'green-text': selectedType === 'oauth' }">无限期使用</view>
			</view>
		</view>

		<!-- 授权状态 -->
		<view v-if="selectedType === 'oauth'">
			<view class="auth-status" @click="handleAuthorize">
				<view class="status-text">应用授权</view>
				<view v-if="true" class="status-value">未授权</view>
				<view v-else class="status-value" style="color:#00C853;">已授权</view>
			</view>

			<!-- <view style="color: #00C853;font-size: 26rpx;text-decoration: underline;margin-left: 450rpx;">
				<text @click="handleHelp">如何获取应用授权?</text>
			</view> -->
		</view>
		<view v-else>
			<view class="auth-status" @click="handleAuthorize">
				<view class="status-text">访问令牌</view>
				<view v-if="!isToken" class="status-value">未授权</view>
				<view v-else class="status-value" style="color:#00C853;">已授权</view>
			</view>

			<!-- <view style="color: #00C853;font-size: 26rpx;text-decoration: underline;margin-left: 450rpx;">
				<text @click="handleHelp">如何获取访问令牌?</text>
			</view> -->
		</view>

		<!-- 添加两种模态框组件 -->
		<OAuthModal v-show="showOAuthModal" @confirm="handleOAuthConfirm" @cancel="handleOAuthCancel"
			@handleHelp="handleHelp" />

		<TokenModal v-show="showTokenModal" @confirm="handleTokenConfirm" @cancel="handleTokenCancel"
			@handleHelp="handleHelp" :tokenValue="access_token" />

		<view v-if="isToken && spaceList">
			<!-- 空间名称部分 -->
			<view class="section-title">空间名称</view>
			<view class="section-subtitle">仅显示自己的空间</view>
			<view class="section-container" v-if="spaceList">
				<picker @change="handleSpaceChange" :value="spaceIndex" :range="spaceList" range-key="name">
					<view class="select-box">
						<text>{{spaceList[spaceIndex]?.name}}</text>
						<text class="arrow">></text>
					</view>
				</picker>
			</view>

			<!-- 智能体名称部分 -->
			<view class="section-title">智能体名称</view>
			<view class="section-subtitle">仅显示已发布API的智能体</view>
			<view class="section-container" v-if="botList">
				<picker @change="handleBotChange" :value="botIndex" :range="botList" range-key="bot_name">
					<view class="select-box">
						<text>{{botList[botIndex]?.bot_name}}</text>
						<text class="arrow">></text>
					</view>
				</picker>
			</view>

			<!-- 智能体预览卡片 -->
			<view class="bot-preview">
				<view class="bot-header">
					<image class="bot-avatar" :src="botList[botIndex]?.icon_url" mode="aspectFill"></image>
					<text class="bot-name">{{botList[botIndex]?.bot_name}}</text>
				</view>
				<view class="divider"></view>
				<view class="bot-info">
					<text class="bot-desc">{{botList[botIndex]?.description}}</text>
				</view>
			</view>

			<!-- 底部按钮组 -->
			<view class="bottom-buttons">
				<button class="preview-btn" @click="handlePreview(botIndex)">
					<text class="btn-icon">👁️</text>
					<text>预览</text>
				</button>
				<button class="publish-btn" @click="handlePublish(botIndex)">
					<text class="btn-icon">⚡</text>
					<text>发布</text>
				</button>
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import OAuthModal from '@/components/OAuthModal.vue'
	import TokenModal from '@/components/TokenModal.vue'
	import {
		aiApi,
		userApi
	} from '../../utils/api';

	const selectedType = ref('token') // 默认选中token  OAuth
	const showOAuthModal = ref(false)
	const showTokenModal = ref(false)
	const selectedBot = ref('')
	const isAuthorized = ref(false) //区分显示token和aouth
	const isToken = ref(false)// 用于控制是否显示下半部分内容
	const access_token = ref(null)
	// 修改选择相关的响应式变量
	const spaceIndex = ref(0)
	const botIndex = ref(0)

	// 为不同空间配置不同的智能体列表
	const botListMap = {

	}
	// 修改数据结构
	const spaceList = ref([])

	// 使用计算属性获取当前空间对应的智能体列表
	const botList = ref([])

	// 获取用户信息的异步函数
	const getUserMessages = async () => {
		const userInfo = await userApi.getUserInfo()
		if (userInfo.data.coze_access_token) {
			access_token.value = userInfo.data.coze_access_token
			if(access_token.value){
				handleTokenConfirm(access_token.value)
				
			}else{
				isToken.value = false;
			}
			
		}
	}
	onMounted(() => {
		
		getUserMessages()
	})

	const selectType = (type) => {
		selectedType.value = type
		if (type == "token") {
			isAuthorized.value = true
		} else {
			isAuthorized.value = false;
		}
		console.log(type, isAuthorized.value)
	}

	const handleAuthorize = () => {
		if (selectedType.value === 'oauth') {
			showOAuthModal.value = true
		} else {
			showTokenModal.value = true
		}
	}

	const handleOAuthConfirm = async(data) => {
		console.log('OAuth数据：', data)
		showOAuthModal.value = false
		const res =await aiApi.setCozeOAuth(data);
	}

	const handleOAuthCancel =  () => {
		showOAuthModal.value = false
	}
	/**
	 * @name 个人token点击按钮事件
	 * @description  
	 * @param {Object} token
	 */
	async function handleTokenConfirm(token) {
		if(!token){
			return;
		}
		isToken.value =false
		const sendTokenRes = await aiApi.sendAccessToken({
			coze_access_token: token
		})
		if (!sendTokenRes.success) {
			uni.showToast({
				title: sendTokenRes.message,
				icon: 'none'
			})
		} else {
			showTokenModal.value = false
			spaceList.value = []
			
			const botList1 = await aiApi.getMergeList()
			if(botList1){
				spaceList.value = botList1.data;
				botListMap.value = {};
				botList1.data.forEach((item) => {
					botListMap.value[item.id] = item.bots;
				})
				botList.value = botList1.data[0].bots;
				isToken.value = true // 授权成功后显示下半部分内容
			}
			
		}

	}
	const handleTokenCancel = () => {
		showTokenModal.value = false
	}

	const handleHelp = () => {
		uni.navigateTo({
			url: `/pages/publish/how?type=${selectedType.value}`
		})
	}
	const handleHelp2 = () => {

	}
	const handleQuery = () => {
		// 处理查询按钮点击
	}

	// 空间选择处理方法
	const handleSpaceChange = (e) => {
		spaceIndex.value = e.detail.value
		// 更新智能体列表
		const spaceId = spaceList.value[spaceIndex.value].id
		botList.value = botListMap?.value[spaceId]
		// 重置智能体选择索引
		botIndex.value = 0
	}

	// 智能体选择处理方法
	const handleBotChange = (e) => {
		botIndex.value = e.detail.value
		console.log(botIndex.value);
	}
	// 处理预览按钮点击
	/*
	 * 1、预览智能体
	 * 2、跳转对话页面
	 */
	const handlePreview = async (index) => {
		const publishRes = await aiApi.publishAi({
			bot_id: botList.value[index].bot_id,
			is_public: 0
		})
		uni.navigateTo({
			url: '/pages/chat/chat?id=' + botList.value[index].bot_id
		})
	}
	// 处理发布按钮点击
	/*
	 * 1、发布智能体
	 * 2、跳转首页
	 */
	const handlePublish = async (index) => {
		const publishRes = await aiApi.publishAi({
			bot_id: botList.value[index].bot_id,
			is_public: 1
		})
		uni.showToast({
			title: publishRes.message,
			icon: 'none'
		})
		if (publishRes.success) {
			// 延迟跳转，让用户看到成功提示
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 1500);
		}
	}
</script>

<style scoped>
	.publish-page {
		min-height: 100vh;
		background: #f8f9fa;
		padding: 40rpx 30rpx;
	}

	.auth-types {
		padding: 20rpx 0;
		display: flex;
		gap: 24rpx;
	}

	.auth-card {
		flex: 1;
		background: #fff;
		padding: 36rpx;
		border-radius: 24rpx;
		border: 2rpx solid transparent;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.auth-card.active {
		border-color: #00C853;
		transform: translateY(-2rpx);
		box-shadow: 0 8rpx 24rpx rgba(0, 200, 83, 0.15);
	}

	.auth-title {
		font-size: 34rpx;
		font-weight: 600;
		margin-bottom: 24rpx;
		color: #2c3e50;
	}

	.auth-desc {
		font-size: 28rpx;
		color: #606f7b;
		margin-bottom: 12rpx;
	}

	.auth-limit {
		font-size: 26rpx;
		color: #8795a1;
	}

	.green-text {
		color: #00C853;
	}

	.auth-status {
		margin: 24rpx 0;
		padding: 32rpx;
		background: #fff;
		border-radius: 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.status-text {
		font-size: 30rpx;
		color: #333;
	}

	.status-value {
		font-size: 30rpx;
		color: #999;
	}

	.input-section {
		margin: 20rpx 0;
		position: relative;
	}

	.auth-input {
		width: 92%;
		height: 96rpx;
		background: #fff;
		border-radius: 20rpx;
		padding: 0 32rpx;
		font-size: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.help-link {
		position: absolute;
		right: 20rpx;
		bottom: -50rpx;
	}

	.help-link text {
		color: #00C853;
		font-size: 26rpx;
		text-decoration: none;
		border-bottom: 2rpx solid #00C853;
		padding-bottom: 4rpx;
	}

	.bottom-button {
		position: fixed;
		bottom: 40rpx;
		left: 30rpx;
		right: 30rpx;
	}

	.query-btn {
		width: 100%;
		height: 90rpx;
		background: #00C853;
		color: #fff;
		border-radius: 45rpx;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.help-text {
		text-align: right;
		padding-right: 30rpx;
		margin-top: 20rpx;
	}

	.help-text text {
		color: #00C853;
		font-size: 26rpx;
		text-decoration: underline;
	}

	.section-title {
		font-size: 30rpx;
		color: #2c3e50;
		font-weight: 600;
		margin: 36rpx 0 12rpx 8rpx;
	}

	.section-subtitle {
		font-size: 26rpx;
		color: #8795a1;
		margin: 0 0 16rpx 8rpx;
	}

	.section-container {
		background: #fff;
		border-radius: 24rpx;
		padding: 24rpx;
		margin: 0 0 32rpx 0;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.select-box {
		height: 92rpx;
		border-radius: 16rpx;
		padding: 0 32rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		transition: background-color 0.3s ease;
	}

	.select-box:active {
		background: #f1f3f5;
	}

	.arrow {
		color: #999;
		font-size: 28rpx;
	}

	.bot-preview {
		margin: 32rpx 0;
		padding: 32rpx;
		background: #fff;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.bot-header {
		display: flex;
		align-items: center;
		padding-bottom: 24rpx;
	}

	.bot-avatar {
		width: 88rpx;
		height: 88rpx;
		border-radius: 44rpx;
		margin-right: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.bot-name {
		font-size: 34rpx;
		color: #2c3e50;
		font-weight: 600;
	}

	.divider {
		height: 2rpx;
		background: linear-gradient(to right, #f1f3f5, #e9ecef, #f1f3f5);
		margin: 4rpx 0;
	}

	.bot-info {
		padding-top: 20rpx;
	}

	.bot-desc {
		font-size: 28rpx;
		color: #606f7b;
		line-height: 1.7;
	}

	.bottom-buttons {
		position: fixed;
		bottom: 48rpx;
		left: 40rpx;
		right: 40rpx;
		display: flex;
		gap: 32rpx;
	}

	.preview-btn,
	.publish-btn {
		height: 96rpx;
		border-radius: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
		font-weight: 600;
		gap: 12rpx;
		border: none;
		transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	}

	.btn-icon {
		font-size: 32rpx;
		margin-right: 5rpx;
	}

	.preview-btn {
		width: 35%;
		background: linear-gradient(135deg, #FFB300, #FF9800);
		color: #fff;
		box-shadow: 0 4rpx 16rpx rgba(255, 179, 0, 0.3);
	}

	.publish-btn {
		width: 50%;
		background: linear-gradient(135deg, #00C853, #00B248);
		color: #fff;
		box-shadow: 0 4rpx 16rpx rgba(0, 200, 83, 0.3);
	}

	.preview-btn:active,
	.publish-btn:active {
		transform: translateY(2rpx);
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
	}
</style>
